package com.guoheng.hazard.manager.subsystem;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guoheng.hazard.common.base.Result;
import com.guoheng.hazard.common.enums.ErrorCodeEnum;
import com.guoheng.hazard.sys.model.dto.subsystem.*;
import lombok.Data;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

import static com.guoheng.hazard.manager.subsystem.SubSystemConfig.LDAR_GET_TOKEN;

/**
 * @program: safe
 * @description: 子系统登录管理
 * @author: fbl
 * @create: 2019-11-06 17:15
 **/
@Component
@Data
public class SubsystemManager {
    /**
     * 智慧环保token
     */
    private String environmentalToken;

    /**
     * ldar获取token
     */
    private String ldarToken;

    /**
     * 获取子系统带token的登录url
     *
     * @return Result
     * @author fbl
     * @date 2019/11/6 2019/11/6
     */
    public Result getLoginUrl() {
        SubsystemUrlDTO subsystemUrlDTO = new SubsystemUrlDTO();

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("username", SubSystemConfig.USERNAME);
        paramMap.put("password", SubSystemConfig.PASSWORD);
        try {
            // 智慧环保
            // 智慧环保获取token
            String environmentalResult = HttpUtil.get("http://192.168.10.7:8200/portal/api/get/token.do" + "?username=" + paramMap.get("username") + "&password=" + paramMap.get("password"));
            JSONObject environmentalJson = JSON.parseObject(environmentalResult);
            String environmentalCode = environmentalJson.getString("code");
            if (!"200".equals(environmentalCode)) {
                return Result.failure();
            }
            environmentalToken = environmentalJson.getString("token");
        } catch (Exception e) {
            return Result.failure(ErrorCodeEnum.SYS_ERR_CONNECTION_TIME_OUT);
        }

        EnvironmentalDTO environmentalDTO = new EnvironmentalDTO();
        // 智慧环保登录url
        environmentalDTO.setEnvironmentalLogin(SubSystemConfig.ENVIRONMENTAL_LOGIN + "?token=" + environmentalToken);
        // 环保一张图
        environmentalDTO.setEnvironmentalMap(SubSystemConfig.ENVIRONMENTAL_MAP + "?token=" + environmentalToken);
        // 智能监测
        environmentalDTO.setCapacityMonitoring(SubSystemConfig.CAPACITY_MONITORING + "?token=" + environmentalToken);
        // 数据研判
        environmentalDTO.setDataResearch(SubSystemConfig.DATA_RESEARCH + "?token=" + environmentalToken);
        // 污染溯源
        environmentalDTO.setPolluteSource(SubSystemConfig.POLLUTE_SOURCE + "?token=" + environmentalToken);

        subsystemUrlDTO.setEnvironmentalDTO(environmentalDTO);

        // 智慧应急
        EmergencyDTO emergencyDTO = new EmergencyDTO();
        emergencyDTO.setEmergency(SubSystemConfig.EMERGENCY);

        subsystemUrlDTO.setEmergencyDTO(emergencyDTO);

        // 封闭园区
        GardenDTO gardenDTO = new GardenDTO();
        gardenDTO.setGarden(SubSystemConfig.GARDEN + "?username=" + paramMap.get("username") + "&password=" + paramMap.get("password"));

        subsystemUrlDTO.setGardenDTO(gardenDTO);
        // 综合管控
        // idar获取token
        try {
            String idarResult = HttpUtil.post(LDAR_GET_TOKEN, paramMap);
            JSONObject idarJson = JSON.parseObject(idarResult);
            String idarCode = idarJson.getString("code");
            if (!"200".equals(idarCode)) {
                return Result.failure();
            }
            ldarToken = idarJson.getString("token");
        }catch (Exception e){
            return Result.failure(ErrorCodeEnum.SYS_ERR_CONNECTION_TIME_OUT);
        }

        SynthesisMonitoring synthesisMonitoring = new SynthesisMonitoring();
        // idar登录路径
        synthesisMonitoring.setLdar(SubSystemConfig.LDAR + "?token=" + ldarToken);
        // 一园一档
        synthesisMonitoring.setOneGrandOneFile(SubSystemConfig.ONE_GRAND_ONE_FILE);
        // 分级预警
        synthesisMonitoring.setLevelAlarm(SubSystemConfig.LEVEL_ALARM);
        // 工程监控
        synthesisMonitoring.setWorkingMonitoring(SubSystemConfig.WORKING_MONITORING);
        subsystemUrlDTO.setSynthesisMonitoring(synthesisMonitoring);

        // 风险管控
        RiskMonitoring riskMonitoring = new RiskMonitoring();
        String riskResult = HttpUtil.get(SubSystemConfig.RISK_MONITORING);
        JSONObject riskJson = JSON.parseObject(riskResult);
        String riskMessage = riskJson.getString("message");

        riskMonitoring.setRiskMonitoring("http://121.40.159.220:8082/wzrmac/" + riskMessage + "?username=" + paramMap.get("username") + "&password=" + SubSystemConfig.PASSWORD_PLAINTEXT);
        subsystemUrlDTO.setRiskMonitoring(riskMonitoring);
        return Result.success(subsystemUrlDTO);
    }

    public Result loginOut() {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("username", SubSystemConfig.USERNAME);
        paramMap.put("password", SubSystemConfig.PASSWORD);

        try {
            // 智慧环保
            String environmentalPost = HttpUtil.get("http://192.168.10.7:8200/portal/api/clear/token.do?token=" + environmentalToken);
            JSONObject environmentalPostJson = JSONObject.parseObject(environmentalPost);
            String environmentalCode = environmentalPostJson.getString("code");
            if (!"200".equals(environmentalCode)) {
                return Result.failure();
            }
            //idar
            String idarPost = HttpUtil.post("http://www.vocs-sz.com/wz/index.php?m=api&a=cancelToken", paramMap);
            JSONObject idarJson = JSONObject.parseObject(idarPost);
            String idarCode = idarJson.getString("code");
            if (!"200".equals(idarCode)) {
                return Result.failure();
            }
        }catch (Exception e){
            return Result.failure(ErrorCodeEnum.SYS_ERR_CONNECTION_TIME_OUT);
        }
        return Result.success();
    }

    public Result airQuality(){
        AirQualityDTO airQualityDTO = new AirQualityDTO();
        try {
            // 得到园区空气质量
            String realAqi = HttpUtil.get(SubSystemConfig.REAL_AQI);
            JSONObject airJsonObject = JSONObject.parseObject(realAqi);
            String dateTime = airJsonObject.getString("dateTime");
            airQualityDTO.setDateTime(dateTime);
            String aqi = airJsonObject.getString("aqi");
            JSONObject aqiJsonObject = JSONObject.parseObject(aqi);
            Integer aqiValue = aqiJsonObject.getInteger("aqiValue");
            Integer optionalAqiValue = Optional.ofNullable(aqiValue).orElse(26);
            airQualityDTO.setAqiValue(optionalAqiValue);
            String mainPolluter = aqiJsonObject.getString("mainPolluter");
            String optionalMainPolluter = Optional.ofNullable(mainPolluter).orElse("No");
            airQualityDTO.setMainPolluter(optionalMainPolluter);
            Integer status = aqiJsonObject.getInteger("status");
            if(status.equals(0)){
                status = 1;
            }
            airQualityDTO.setStatus(status);


            // 获取优良天数和首要污染物统计
            String goodDaysPolluteStatistics = HttpUtil.get(SubSystemConfig.GOOD_DAYS_POLLUTE);
            JSONObject statisticsJsonObject = JSONObject.parseObject(goodDaysPolluteStatistics);
            Integer total = statisticsJsonObject.getInteger("total");
            airQualityDTO.setTotal(total);
            String rate = statisticsJsonObject.getString("rate");
            airQualityDTO.setRate(rate);
            Integer goodDays = statisticsJsonObject.getInteger("goodDays");
            airQualityDTO.setGoodDays(goodDays);
            String pollute = statisticsJsonObject.getString("pollute");
            JSONObject polluteJsonObject = JSONObject.parseObject(pollute);
            String noTwo = polluteJsonObject.getString("NO2");
            airQualityDTO.setNoTwo(noTwo);
            String oThree = polluteJsonObject.getString("O3");
            airQualityDTO.setOThree(oThree);
            String soTwo = polluteJsonObject.getString("SO2");
            airQualityDTO.setSoTwo(soTwo);
            String pmTwoDotFive = polluteJsonObject.getString("PM2.5");
            airQualityDTO.setPmTwoDotFive(pmTwoDotFive);
            String pmTen = polluteJsonObject.getString("PM10");
            airQualityDTO.setPmTen(pmTen);
            String co = polluteJsonObject.getString("CO");
            airQualityDTO.setCo(co);
        }catch (Exception e){
            return Result.failure(ErrorCodeEnum.SYS_ERR_CONNECTION_TIME_OUT);
        }
        return Result.success(airQualityDTO);
    }

    public Result waterQuality(){
        ArrayList<WaterQualityDTO> waterQualityDTOS = new ArrayList<>();

        try {
            String waterQuality = HttpUtil.get(SubSystemConfig.WATER_QUALITY);
            List<SubsystemWaterQualityDTO> subsystemWaterQualityDTOS = JSONArray.parseArray(waterQuality, SubsystemWaterQualityDTO.class);
            for (SubsystemWaterQualityDTO qualityDTO : subsystemWaterQualityDTOS) {
                WaterQualityDTO waterQualityDTO = new WaterQualityDTO();
                // 各个级水质对应数量
                Integer level1 =qualityDTO.getLevel1();
                waterQualityDTO.setLevelOne(level1);

                Integer level2 = qualityDTO.getLevel2();
                waterQualityDTO.setLevelTwo(level2);

                Integer level3 = qualityDTO.getLevel3();
                waterQualityDTO.setLevelThree(level3);

                Integer level4 = qualityDTO.getLevel4();
                waterQualityDTO.setLevelFour(level4);

                Integer level5 = qualityDTO.getLevel5();
                waterQualityDTO.setLevelFive(level5);

                Integer level6 = qualityDTO.getLevel6();
                waterQualityDTO.setLevelSix(level6);

                // 点位名称
                waterQualityDTO.setSiteName(qualityDTO.getSiteName());

                // 是否是上游
                String siteName = qualityDTO.getSiteName();
                if(siteName.contains("上")){
                    waterQualityDTO.setUpFlag(true);
                }else {
                    waterQualityDTO.setUpFlag(false);
                }

                // 溶解氧
                waterQualityDTO.setDissolveOxygen(qualityDTO.get溶解氧());
                // 氨氮
                waterQualityDTO.setAmmoniaNitrogen(qualityDTO.get氨氮());
                // 目标水质级别 1-6
                waterQualityDTO.setStandardLevel(qualityDTO.getStandardLevel());
                // 总磷
                waterQualityDTO.setTotalPhosphorus(qualityDTO.get总磷());
                // 水质级别  1-6
                waterQualityDTO.setThisLevel(qualityDTO.getLevelId());
                // ph值
                waterQualityDTO.setPH(qualityDTO.getPH());
                // 是否超标
                Integer isOver = qualityDTO.getIsOver();
                if(isOver == 1){
                    waterQualityDTO.setOverFlag(true);
                }else {
                    waterQualityDTO.setOverFlag(false);
                }
                // 高锰酸盐指数
                waterQualityDTO.setPermanganate(qualityDTO.get高锰酸盐指数());
                // 参与评价的因子名称
                String itemNames = qualityDTO.getItemNames();
                String[] split = itemNames.split(",");
                List<String> names = Arrays.asList(split);
                waterQualityDTO.setItemNames(names);
                // 总氮
                waterQualityDTO.setTotalNitrogen(qualityDTO.get总氮());

                waterQualityDTOS.add(waterQualityDTO);
            }
        }catch (Exception e){
            return Result.failure(ErrorCodeEnum.SYS_ERR_CONNECTION_TIME_OUT);
        }
        return Result.success(waterQualityDTOS);
    }
}